<template>
  <div class="main">
    <a-form id="formLogin" class="user-layout-login" ref="formLogin" :form="form" @submit="handleSubmit">
      <a-form-item>
        <a-input
          size="large"
          type="text"
          placeholder="请输入您的手机号"
          v-decorator.lazy="[
            'phone',
            {
              rules: [{ required: true, message: $t('user.phone-number.required') }],
              validateTrigger: 'change',
            },
          ]"
        >
          <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)', fontSize: '16px' }" />
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-input
          size="large"
          type="text"
          placeholder="请输入短信验证码"
          v-decorator="[
            'phoneCode',
            { rules: [{ required: true, message: '请输入图形验证码' }], validateTrigger: 'change' },
          ]"
        >
          <a-icon slot="prefix" type="picture" :style="{ color: 'rgba(0,0,0,.25)', fontSize: '16px' }" />
          <template #addonAfter>
            <div v-if="phoneCode.timeOut" class="phoneCode-wrap">
              <!-- <img :src="picCode.codeImg" alt="" /> -->
              {{ phoneCode.time }} 秒
            </div>
            <a-button v-else type="link" @click="getPhoneCodeSlide" :loading="phoneCode.loading">获取验证码</a-button>
          </template>
        </a-input>
      </a-form-item>

      <a-form-item>
        <a-input-password
          size="large"
          :placeholder="$t('user.login.new.password.placeholder')"
          v-decorator="[
            'password',
            { rules: [{ required: true, message: $t('user.password.required') }], validateTrigger: 'blur' },
          ]"
        >
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)', fontSize: '16px' }" />
        </a-input-password>
      </a-form-item>
      <!-- :placeholder="$t('user.login.username.placeholder')"  $t('user.userName.required') }]-->
      <!-- <a-form-item>
        <a-input
          size="large"
          type="text"
          placeholder="请输入图形验证码"
          v-decorator="[
            'picCode',
            { rules: [{ required: true, message: '请输入图形验证码' }], validateTrigger: 'change' },
          ]"
        >
          <a-icon slot="prefix" type="picture" :style="{ color: 'rgba(0,0,0,.25)', fontSize: '16px' }" />
          <template #addonAfter v-if="form.getFieldValue('account')">
            <a-spin :spinning="picCode.loading">
              <div @click="getPicCode" class="picCode-wrap">
                <img :src="picCode.codeImg" alt="" />
              </div>
            </a-spin>
          </template>
        </a-input>
      </a-form-item> -->
      <a-form-item style="malrgin-top: 35px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="state.loginBtn"
          :disabled="state.loginBtn"
          > 确认 </a-button
        >
      </a-form-item>
    </a-form>
    <div class="psw-reg">
      <p class="link-text"><router-link to="/user/login">去登录</router-link></p>
    </div>
    <slide-verify
      :visible="slide.visible"
      slider-text="拖动左边滑块完成上方拼图"
      @success="getPhoneCode"
      @failed="onFail"
      @cancel="handleCancel('slide')"
    >
    </slide-verify>
  </div>
</template>

<script>
import md5 from 'md5'
import { mapActions, mapGetters } from 'vuex'
import { timeFix } from '@/utils/util'
import { BASICURL } from '@/utils/state-string'
import { userForgetPassword, userGetVerifyCode, userCheckVerifyCode } from '@/api/user'
import SilderVerify from '@/components/AWMSliderVerify'
import { jm } from '@/utils/util'

export default {
  components: {
    'slide-verify':SilderVerify
  },
  data() {
    return {
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      picCode: {
        codeImg: '',
        loading: false,
      },
      wxStatus: {
        visible: false,
        confirmLoading: false,
      },
      phoneStatus: {
        visible: false,
        confirmLoading: false,
      },
      timeOut: null,
      state: {
        check: false,
        error: '',
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false,
      },
      phoneCode: {
        loading: false,
        time: 0,
        timeOut: null,
      },
      slide:{
        visible: false,
      }
    }
  },
  computed: {
    ...mapGetters({ userInfo: 'userInfo' }),
  },
  created() {},
  methods: {
    ...mapActions(['Login', 'Logout']),
    getPhoneCodeSlide(){
      let self = this
      self.form.validateFields(['phone'], (error, values) => {
        if (error) return false
        this.slide.visible = true
      })
    },
    getPhoneCode() {
      let self = this
      self.form.validateFields(['phone'], (error, values) => {
        console.log(error, values)
        setTimeout(()=>{
          this.slide.visible = false
        },1000)
        if (error) return false

        // let phone = self.form.getFieldValue('phone')
        values.verifyToken = jm(values.phone)
        self.phoneCode.loading = true
        console.log(userGetVerifyCode)
        userGetVerifyCode(values)
          .then((res) => {
            self.phoneCode.time = 60
            self.phoneCode.timeOut = setInterval(() => {
              self.phoneCode.time--
              if (self.phoneCode.time <= 0) {
                clearInterval(self.phoneCode.timeOut)
                self.phoneCode.timeOut = null
              }
            }, 1000)
          })
          .finally(() => {
            self.picCode.loading = false
          })
        // if (!phone) {
        //   this.$message.warning('请输入手机号')
        //   return false
      })
    },
    handleGetPicCode(e) {
      if (this.timeOut) {
        clearTimeout(this.timeOut)
        this.timeOut = null
      }
      this.timeOut = setTimeout(() => {
        this.getPicCode()
        clearTimeout(this.timeOut)
        this.timeOut = null
      }, 1000)
    },
    handleUsernameOrEmail(rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleTabClick(key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },
     handleSubmit(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
      } = this
      // if(!state.check) {
      //   this.$message.error('阅读并勾选平台协议与隐私政策')
      //   // state.error = 'error'
      //   // this.$forceUpdate()
      //   return false
      // }
      state.loginBtn = true

      // const validateFieldsKey = customActiveKey === 'tab1' ? ['account', 'password', 'picCode'] : ['mobile', 'captcha']
      validateFields(['phone', 'phoneCode'], (error, values1) => {
        if (error) {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
          return false
        }
        // if(res)

        console.log(values1)
        let checkParams = { ...values1 }
        userCheckVerifyCode(checkParams)
          .then((checkRes) => {
            if (checkRes.code != 1) {
              setTimeout(() => {
                state.loginBtn = false
              }, 600)
              this.$message.error(checkRes.msg)
              return false
            }

            validateFields(['password', 'phone', 'name'], { force: true }, (err, values2) => {
              if (!err) {
                const loginParams = { ...values2 }
                console.log(loginParams)
                loginParams.codeToken = checkRes.data.codeToken || ''
                // 邀请人  待添加
                loginParams.inviteId = ''
                console.log(loginParams);
                userForgetPassword(loginParams)
                  .then((registerRes) => {
                    if(registerRes.code == 1){
                      this.Success(registerRes)
                      this.$message.success('修改成功')
                    }else{
                      this.$message.error(registerRes.msg)
                    }
                    
                  })
                  .finally(() => {
                    state.loginBtn = false
                  })
              } else {
                setTimeout(() => {
                  state.loginBtn = false
                }, 600)
              }
            })
          })
          .catch((err) => {
            setTimeout(() => {
              state.loginBtn = false
            }, 600)
          })
      })
    },
    handlePhoneOk() {
      const form = this.$refs.phoneModal.form
      this.phoneStatus.confirmLoading = true
      const { state } = this
      form.validateFields((errors, values) => {
        let pdata = {
          ...values,
          account: this.phoneStatus.account,
        }
        state.loginBtn = true
        this.$store
          .dispatch('PhoneCheck', pdata)
          .then((res) => {
            this.Success()
          })
          .catch((err) => {
            this.requestFailed(err)
          })
          .finally(() => {
            state.loginBtn = false
          })
        if (!errors) {
        } else {
          this.phoneStatus.confirmLoading = false
        }
      })
    },
    stepCaptchaSuccess() {
      this.Success()
    },
    stepCaptchaCancel() {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    Success(res) {
      console.log(BASICURL);
      this.$router.push({ path: '/user/login' })
      // 延迟 1 秒显示欢迎信息
      this.isLoginError = false
    },
    requestFailed(err) {
      this.isLoginError = true
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).msg || '请求出现错误，请稍后再试',
        duration: 4,
      })
    },
    handleCancel(key) {
      this[key].visible = false
    },
    onSuccess() {console.log('success');},
    onFail() {console.log('Fail');},
  },
}
</script>

<style lang="less" scoped>
.main{
  /deep/ .ant-input{
    padding-left: 35px;
  }
}

.top {
  text-align: center;

  .header {
    height: 44px;
    line-height: 44px;

    .badge {
      position: absolute;
      display: inline-block;
      line-height: 1;
      vertical-align: middle;
      margin-left: -12px;
      margin-top: -10px;
      opacity: 0.8;
    }

    .logo {
      height: 44px;
      vertical-align: top;
      margin-right: 16px;
      border-style: none;
    }

    .title {
      font-size: 33px;
      color: rgba(0, 0, 0, 0.85);
      font-family: Avenir, 'Helvetica Neue', Arial, Helvetica, sans-serif;
      font-weight: 600;
      position: relative;
      top: 2px;
    }
  }
  .desc {
    font-size: 14px;
    color: rgba(0, 0, 0, 0.45);
    margin-top: 12px;
    margin-bottom: 40px;
  }
}
.padding-wrap {
  padding: 0 10px;
}
.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }
    .register {
      float: right;
    }
  }
}
.picCode-wrap {
  min-width: 80px;
}
.psw-reg{
  display: flex;
  justify-content: space-between;
  .link-text{
  text-align: center;
  font-size: 14px;
}
}

</style>
